<template>
  <div id="p_taskSimple" class="p_task">
    <group v-show="sindex==0" v-for="(group, indexg) in groups" :key="indexg" :title="group.title" :class="'group'+(group?group.day:'')">
        <swipeout>  <!---->
            <swipeout-item @touchstart.native="showSwipeIndex=indexg+'_'+index" @on-open="actionOpen(item, indexg, index)" v-for="(item, index) in group.tasks" :key="indexg+'_'+index" :ref="'action'+indexg">
                <div v-show="showSwipeIndex==indexg+'_'+index" slot="right-menu">
                    <!-- <swipeout-button v-if="item.state=='done'" @click.native="onTaskEidt(item,'')" type="primary">取消完成</swipeout-button>
                    <swipeout-button v-if="item.state!='done'" @click.native="onTaskEidt(item,'done')" type="primary">完成</swipeout-button> -->
                    <swipeout-button @click.native="goTask(item,index)" type="warn">修改</swipeout-button>
                    <swipeout-button @click.native="onDelClick(item,index)" type="default">取消任务</swipeout-button>
                </div>
                <div v-show="showSwipeIndex==indexg+'_'+index" slot="left-menu">
                    <swipeout-button type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                </div>
                <div slot="content" class="vux-1px-t" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskCurr == item}">
                    <cell @click.native="onEdit(item,index)" :title="showTaskTitle(item)" :inline-desc="item.state!=''?showTaskDesc1(item):item.desc">
                      <div slot="icon">
                          <img :src="showIcons(item)" style="width:50px;height:50px;"/>
                          <span class="taskCount">{{index+1 + "/" + group.tasks.length}}</span>
                      </div>
                    </cell>
                </div>
            </swipeout-item>
        </swipeout>
    </group>
    <!--<task-add :show="showTaskAdd" :ext="taskAddExt" type="mode1" v-on:toVisible="taskAddVis"></task-add>
    <x-button v-show="showModeBtn" style="bottom:62px;" class="taskAdd" type="primary" ><span style="font-size:22px;padding-right: 8px;" class="icon iconfont icon-neirongqiehuan"></span></x-button>
    <x-button style="bottom:6px;" class="taskAdd" @click.native="clickAdd" type="primary" ><span style="font-size:22px;padding-right: 8px;" class="icon iconfont icon-tianjia2"></span></x-button>--> 
    <login-win v-show="showLogin" v-on:toVisible="loginWinVis"></login-win>
    <actionsheet v-model="showEditBtn" :menus="asBtnCurr" show-cancel @on-click-menu="chooseEdit"></actionsheet>

  </div>
</template>
<script>
import moment from "moment";
import _ from "../../static/jslib/underscore-min.js";
import Vue from 'vue';
import TaskMd from "./life/TimeTaskMD.vue" ;

import api from '../api';
import {
    mapState,
    mapActions
} from 'vuex'

import { taskAndTag } from "./mixin";
import { help } from "./mixinApp";
import TaskAdd from "./TaskAdd";
import LoginWin from "./LoginWin";

import {
    Toast,Swipeout,SwipeoutItem,SwipeoutButton,XButton,Group,Cell,Tab,TabItem,Actionsheet,
    Box,XInput,XTextarea,Flexbox, FlexboxItem,Datetime,Scroller,ButtonTab,ButtonTabItem
} from 'vux'

var defaultTask = [{title:"待办任务",day:"",tasks:[{title:"创建任务:点击下方'+'",desc:""},{title:"完成:点击一下",desc:""},{title:"取消完成:再点击一下",desc:""}]}
    ];

export default {
    components: {        
        Toast,Swipeout,SwipeoutItem,SwipeoutButton,XButton,Group,Cell,Tab,TabItem,Actionsheet,TaskMd,
        Box,XInput,XTextarea,Flexbox, FlexboxItem,Datetime,Scroller,ButtonTab,ButtonTabItem,TaskAdd,LoginWin
    },   
    mixins: [taskAndTag,help],    
    computed: {        
        ...mapState({
            uid: state => state.vux.uid,
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
                        
            tagitemDic: state => state.z39.tagitemDic,
        })
    },
    watch: {
        "taskAll":{handler(){
            console.log("watch taskAll",this.taskAll.length);
            this.nonesCpted();
        },  deep: true },
        "uid":function(){
            this.getInitData();
        }
    },
    activated () {
        var lastPos = parseInt(localStorage.getItem("taskOnePos")) || 0;
        setTimeout(()=>{document.querySelector(`#vux_view_box_body`).scrollTop = lastPos },50) 
		this.$store.commit({ type: "z39/addTaskExt", value: {} });
        console.log("activated",lastPos);
    },
    created() {
        this.getData();
        document.querySelector('#vux_view_box_body').scrollTop = 0 ;
        this.initPage();
        this.check2showLogin();
        // this.delayHideMode() ;
    },
    filters: {  
        
    },
    mounted: function() {        
        this.today = moment().format("YYYY-MM-DD");
        this.getInitData();
    },
    methods: {
		getInitData(){
			if( _.isEmpty(this.tagitemDic) && this.uid >0 ){
				this.tagitemsGet();
			}
		},
        initPage(){
            document.querySelector('#vux_view_box_body').scrollTop = 0 ;
            this.nonesCpted();
        },
        nonesCpted(){
            // console.log("nonesCpted in")
            let temp = [] ;
            let tempDic = {} ;
            var len = this.taskAll.length ;
            var tempTitles = [];
            for(var i=0;i<= len-1 ;i++){
                var item = this.taskAll[i] ;
                if(item.uid != this.uid || item.parid != null) continue ; //不是自己的任务和二级任务不显示
                if(item.tags && item.tags['life'] != undefined) continue;
                if(item.tags && item.tags['due'] != undefined){
                    var due = item.tags['due'] ;
                    due = due.length>10?due.substr(0,10):due;
                    tempDic[due] = tempDic[due] || [] ;
                    tempDic[due].push(item);
                }else{
                    tempDic["nones"] = tempDic["nones"] || [] ;
                    tempDic["nones"].push(item);
                }
                tempTitles.push(item.title);
            }
            if( len<defaultTask[0].tasks.length){  //检查数据是否需要合并
                var canMerge = true ;
                var defaultTitles = defaultTask[0].tasks.map(item=>{
                    return item.title ;
                })
                tempTitles.map(title=>{
                    if( canMerge && defaultTitles.indexOf(title) == -1) canMerge = false ;
                })
                if( canMerge ){                    
                    defaultTask[0].tasks.map(task=>{
                        if(tempTitles.indexOf(task.title) == -1) {
                            tempDic["nones"] = tempDic["nones"] || [] ;
                            tempDic["nones"].push(task);
                        }
                    })
                }
            }
            var tomorrow =moment().add(1,"d").format("YYYY-MM-DD");
            // 需要重新排序
            var title,day,nones ;
            title="待办任务";
            day = "";
            nones= {title:title,day:day,tasks:tempDic["nones"]};
            for(var key in tempDic){
                if(key == "nones"){  //待办任务
                    continue ;
                }
                if(key == this.today ){
                    title="今天:"+key;
                }else if(key == tomorrow ){
                    title="明天:"+key;
                }else{
                    title=key;
                }
                day = key;
                temp.push({title:title,day:day,tasks:tempDic[key]});
                // console.log("taskone:",title,key);
            }
            var sortDay = function(a,b){
                return a.day>b.day;
            }
            if(temp.length>0 && len > 0){
                temp = temp.sort(sortDay) ;
                temp.unshift(nones);
            }else if( len > 0 ){
                temp.unshift(nones);
            }
            var lastPos = parseInt(localStorage.getItem("taskOnePos")) || 0;
            var pos = document.querySelector(`#vux_view_box_body`).scrollTop;
            temp = temp.length>0?temp:defaultTask ;
            this.groups = temp ;
            if(pos==0) this.autoPos(lastPos);
            // console.log("nonesCpted in ",temp.length);
            return temp;
        },
        autoPos(pos){
            this.$nextTick(() => {
                let item = document.querySelector(`#p_taskSimple .group${this.today}`);
                // let page = document.querySelector(`#p_taskSimple`);
                let top = item?item.offsetTop:0; 
                top = Math.max(0,top-60);
                document.querySelector(`#vux_view_box_body`).scrollTop = pos || top ;
            }); 
        },
        onShowTaskBtns(item){
            this.showEditBtn = true ;
            var temp = this.getTaskBtns(item,1) ;
            this.asBtnCurr = temp;
        },
        onEdit(item,index){
            this.taskCurr = item ;
			var ext ;
            if(item.tags && item.tags.due){
                ext = {state:"due",tags:{due:item.tags.due.substr(0,10)}}
            }else{
                ext = {};
            }
			this.taskAddExt = ext ;
			this.$store.commit({ type: "z39/addTaskExt", value: ext });
            if(!item.id) return this.addDemoTask(item);  // this.$vux.toast.show({text:"请创建任务"});
           
            // if(item.tags && item.tags.due){
                // this.onShowTaskBtns(item);
                // return ;
            // }
            let state = item.state ;
            if (state != "done") {
                this.doTaskEdit(item, "done", moment().format("YYYY-MM-DD HH:mm"));
            } else if (state == "done") {
                this.doTaskEdit(item, "");
            }
            return ;
            let _this = this ;
            let time = moment().format("H");
            time = parseInt(time) ;
            let temp ;
            if( time >= 12 ){
                temp = this.showMonth|| moment().add(1, 'days').format("YYYY-MM-DD");
            }else{
                temp = this.showMonth|| moment().format("YYYY-MM-DD");
            }
            this.$vux.datetime.show({
                cancelText: '取消',
                confirmText: '确定',
                format: 'YYYY-MM-DD',
                startDate: moment().format("YYYY-MM-DD") ,
                value: this.showMonth||temp,
                onConfirm (val) {
                  if(!item.id) return _this.addDemoTask(item); // _this.$vux.toast.show({text:"请创建任务"});
                  _this.showMonth =  val ;
                  _this.doTagSet(item,"due",val).then(data=>{
                    _this.nonesCpted();
                    console.log("doTagSet done");
                  }) ;
                },
                onShow () {
                  console.log('plugin show')
                },
                onHide () {
                  console.log('plugin hide')
                }
              })
            console.log( _.clone(item),temp,moment().format("YYYY-MM-DD")) ;
        },
        addDemoTask(item,look){            
            var now = moment().format("YYYY-MM-DD HH:mm") ;
            var due  = now ;
            var sdata, tags ;
            sdata = {title:item.title,state:"done"} ;
            tags =   {done:now,due:now,created:now} ;
            if(look) {
                sdata.state = "";
                tags = {created:now} ;
            }
            return this.taskAdd(sdata, tags) ;
        },
        onTaskEidt(item,state){            
            if(!item.id) return this.addDemoTask(item); //this.$vux.toast.show({text:"请创建任务"});
            this.doTaskEdit(item,state);
        },
        goTask(item,index){ // 进入任务详情            
            var pos = document.querySelector(`#vux_view_box_body`).scrollTop;
            localStorage.setItem("taskOnePos",pos);
            console.log("goTask pos:",pos);
            if(!item.id) return this.addDemoTask(item,true).then(data=>{
                item.id = data.id ;
                // console.log("item:",data);
                this.$router.push(`/taskDetail/${item.id}`) ;
            }) ; //this.$vux.toast.show({text:"请创建任务"});
            this.$router.push(`/taskDetail/${item.id}`) ;
            // this.$router.push(`taskDetail`) ;
        },
        onDelClick(item,index){
            if(!item.id) return this.addDemoTask(item); //this.$vux.toast.show({text:"请创建任务"});
            this.doTaskEdit(item,"cancelled",moment().format("YYYY-MM-DD HH:mm"));
        },
        actionOpen(item,indexg,index,option){            
            let dir = "" , target , arrIndex = index ;
            target = this.$refs['action'+indexg][index] ;
                dir = target.direction ;
            if( dir == "left"){
                if(!item.id){ 
                    target.close();
                    return this.addDemoTask(item); // this.$vux.toast.show({text:"请创建任务"})
                };
                if( item.state == "done"){
                    this.doTaskEdit(item,"");
                }else{
                    this.doTaskEdit(item,"done",moment().format("YYYY-MM-DD HH:mm")).then(data=>{
                        this.nonesCpted();
                    }) ;
                }
                setTimeout(() => {
                    target.close();
                }, 200);                
            }
        },
        clickAdd(){ 
            var vis = this.check2showLogin(true);
            if(!vis) return ;
            this.showTaskAdd = true ;
            let task = this.taskCurr ;
        },
        check2showLogin(now){  //检查并显示login弹窗
            var slogin = true ;
            var token = localStorage.getItem('token');
            if(!this.uid && !token ){
                if(now){
                    this.showLogin = true ;
                }else{
                    setTimeout(()=>{this.showLogin = true ;},2000);
                }                
                slogin = false ;
            }
            return slogin;
        },
        loginWinVis(val){
            this.showLogin = false ;
            if(val) this.getData(); 
        },
        onBtn(item){

        },
        getData: function() {
            api.taskOne({uid:this.uid}).then(data=>{
                if (data == undefined || data.errno != 0) {
                  if (data == undefined) data = { errmsg: "网络错误" };
                  return this.showNotice(data.errmsg, 'warn');
                }
                data = data.data;
                this.$store.commit({ type: "z39/taskToDB", tasks: data, act: "add" });
                this.nonesCpted();
           })
        },
        loadNext(){
            console.log("loadNext");
        },
        taskAddVis(val){
            this.showTaskAdd = val ;
            this.weekEdit = val ;
        },
        delayHideMode(){
            if(this.timeOutMode !=-1){ 
                clearTimeout( this.timeOutMode);
                this.timeOutMode = -1 ;
            }
            this.timeOutMode = setTimeout(()=>{this.showModeBtn=false},8000);
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            groups:[{title:"待办任务",tasks:[]}],
            sindex:0,
            showLogin:false,
            showModeBtn:true,
            showEditBtn:false ,
            asBtnCurr:[],
            showSwipeIndex:'',
            timeOutMode:-1,
            nonesArr:[] ,
            today:"",
            nonesLen:0,
            showMonth:'',
            taskCurr: null ,
            btnsShow:false ,
            taskArr:[],
            weekSelect:-1,
            weekSelectLast:0,
            monthSelect:0,
            yearSelect:0,
            filterDue:'',
            filtersDue:[],
            mode_vip:false,
            pageIndex: 1 ,
            pageTotal: 2 ,
            pageShowNum:15,
            pageNumOne: 15 ,
              pullupConfig2: {
                content: '上拉加载更多',
                downContent: '松开进行加载',
                upContent: '上拉加载更多',
                loadingContent: '加载中...'
              },
            pullStatus: {
             pullupStatus: 'default',
             pulldownStatus: 'default'
            },
            pullDownConfig2: {
                content: '松开切换模式',
                downContent: 'VIP高级模式',
                upContent: '下拉进入高级模式',
                loadingContent: '切换中...'
              },
            scrollHeight:"-97", //-129,
            showTaskAdd:false,
            taskAddExt:{},
        }
    }
}

</script>
<style scoped>
.day-item {
  border: 1px solid #ececec;
  padding: 5px 15px;
}
.day-item-selected {
  border: 1px solid green;
}
</style>
<style>

</style>
